﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Security.Cryptography;

using Google.Protobuf.Examples.AddressBook;
using System.IO;

using Google.Protobuf;

namespace testClient
{
	class MainClass
	{
		public static Dictionary<System.Type, int> protoIds = new Dictionary<System.Type, int>()
		{
			{typeof(MovePosC2S), 1},
			{typeof(UseSkillC2S), 2},
			{typeof(Data), 3},
		};
		public static Dictionary<int, string> idToProto = new Dictionary<int, string>();


		//private static TcpClient client;
		public static TestUDPClient udpClient;

		private static byte[] buffer = new byte[1024];


		private static async void RecvAsync()
		{
			while (true)
			{
				await udpClient.Receive();
			}

		}




		static void Connect()
		{
			//socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
			Console.WriteLine("BeforeConnect");

			try
			{
				//client = new TcpClient("127.0.0.1", 4040);
				udpClient = new TestUDPClient();
			}
			catch (Exception exp)
			{
				Console.WriteLine("ConnectFail: "+exp.ToString());
				return;
			}

			RecvAsync();

			Send();

		}

		static void Connect2()
		{
			udpClient = new TestUDPClient();
			RecvAsync();
		}

		static void Send()
		{
			while (true)
			{
				var ret = Input();
				if (ret == "close")
				{
					return;
				}
			}
		}

		private static int curFrameId = 1;
		//s pos x y
		//s skill 123 
		//s ...
		static void SendByte(string[] s)
		{
			udpClient.Send(s);

		}

		static void Close()
		{
			udpClient.Close();

		}

		static string Input()
		{
			Console.WriteLine("Please Input:");
			var line = Console.ReadLine();
			var cmds = line.Split(char.Parse(" "));
			var c = cmds[0];
			//c
			//s helloworld
			//close 
			if (c == "c")
			{
				Connect();
			}
			else if (c == "s")
			{
				SendByte(cmds);
			}
			else if (c == "close")
			{
				Close();
			}
			return c;
		}

		public static void ReadControl(object obj)
		{
			var gameControl = obj as GameControl;
			while (true)
			{
				gameControl.Run();
			}
		}
		public static void Main(string[] args)
		{
			var world = new World();
			var gameControl = new GameControl();
			world.gameControl = gameControl;
			gameControl.world = world;
			//readControl();
			var th = new Thread(ReadControl);
			th.Start(gameControl);

			Connect2();
			world.Render(500, 500);

			/*
			while (true)
			{
				var cmd = Input();
				if (cmd == "close")
				{
					break;
				}
			}
			*/

		}
	}
}
